package com.google.code.instrumentation.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

import javassist.CtClass;
import javassist.NotFoundException;

import org.junit.Before;
import org.junit.Test;

public class CompileTimeClassUtilTest {

	private String myClassName;
	private ClassLoader myClassLoader;

	@Before
	public void before() {
		myClassName = this.getClass().getName();
		myClassLoader = this.getClass().getClassLoader();
	}

	@Test
	public void getCtClassForCurrentClassLoaderReturnsThis() throws Exception {
		final CtClass ctClass = CompileTimeClassUtil.getCtClass(myClassLoader,
				myClassName);
		assertNotNull(ctClass);
		final String name = ctClass.getName();
		assertEquals(myClassName, name);
	}

	@Test(expected = NotFoundException.class)
	public void getUnknownClass() throws Exception {
		CompileTimeClassUtil.getCtClass(myClassLoader, "UnknownClass");
	}

	@Test
	public void getCtClassFromDefaultLoader() throws Exception {
		final CtClass ctClass = CompileTimeClassUtil.getCtClass(null,
				myClassName);
		assertNotNull(ctClass);
		assertEquals(myClassName, ctClass.getName());
	}

	@Test
	public void getCtClassFromURLClassLoader() throws Exception {
		final URLClassLoader cl = new URLClassLoader(new URL[] { new File(
				"src/test/resources").toURI().toURL() });
		final String className = "testing.ClassToInstrument";
		final CtClass ctClass = CompileTimeClassUtil.getCtClass(cl, className);
		assertNotNull(ctClass);
	}

	@Test(expected = NotFoundException.class)
	public void getCtClassUsingNullClassname() throws Exception {
		CompileTimeClassUtil.getCtClass(myClassLoader, null);
	}

	@Test
	public void getCtClassGivenClass() throws Exception {
		final CtClass ctClass = CompileTimeClassUtil
				.getCtClassFor(CompileTimeClassUtilTest.class);
		assertNotNull(ctClass);
		assertEquals(CompileTimeClassUtilTest.class.getName(),
				ctClass.getName());
	}

}
